#include "Init.h"
//#include "StartWindown.h"
#include <QWidget>
#include <QApplication>
//#include <QQuickView>
//#include <QQmlEngine>
//#include <QQmlComponent>
//#include <QQmlApplicationEngine>
//#include <QQmlContext>
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QtCore>


void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    bool is_collect_log = false;
    QString text;
    switch (type)
    {
    case QtDebugMsg:

        if (msg.startsWith("sys||"))//sys||信息
        {
            is_collect_log = true;
            QStringList info = msg.split("||");
            text = info.at(1);
        }
        else
        {
            text = QString("Debug:");
        }
        break;

    case QtWarningMsg:
        text = QString("Warning:");
        break;

    case QtCriticalMsg:
        text = QString("Critical:");
        break;

    case QtFatalMsg:
        text = QString("Fatal:");
    }

    if (is_collect_log)
    {
        QFile file("syslog.txt");
        file.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream text_stream(&file);
        text_stream << text.mid(2, text.length() - 3) << "\r\n";
        file.flush();
        file.close();
    }
    else if (text != "Warning")
    {
        QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
        QString current_date = QString("(%1)").arg(current_date_time);
        QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
        QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
        QFile file("initlog.txt");

        file.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream text_stream(&file);
        text_stream << message << "\r\n";
        file.flush();
        file.close();
    }
    mutex.unlock();
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(outputMessage);
    QFile file("initlog.txt");
    file.remove();

    QApplication a(argc, argv);
	/*
    qmlRegisterType<StartWindown>("StartWindown", 1, 0, "StartWindown");

    QQuickView viwer;
    viwer.setFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
    viwer.setColor(QColor(Qt::transparent));

    viwer.setSource(QUrl("qrc:/init/res/emitmask.qml"));
    viwer.show();
	*/
    Init w;
    w.show();

    return a.exec();
}
